package services;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import repositories.RouteRepository;
import domain.Administrator;
import domain.Event;
import domain.Route;

@Service
@Transactional
public class RouteService {

	// Managed repository -----------------------------------------------------
	@Autowired
	private RouteRepository routeRepository;
	
	// Constructor ------------------------------------------------------------
	public RouteService(){
		super();
	}
	
	// Simple CRUD methods ----------------------------------------------------
	public Route create(){
		return new Route();
	}
	
	public void save(Route r){
		Assert.notNull(r,"tried to save a null route");
		
		this.routeRepository.save(r);
	}
	
	public void delete(Route r){
		Assert.notNull(r,"tried to delete a null route");
		Assert.isTrue(this.routeRepository.exists(r.getId()),"tried to delete a route that doesn't exists");
		
		this.routeRepository.delete(r);
	}
	
	// Other business methods -------------------------------------------------
	public Collection<Route> findRoutesByEvent(Event e){
		Assert.notNull(e,"tried to find routes of an event that doesn't exists");
		Assert.isTrue(e.getId()!=0,"tried to find routes of an event with id zero");
		
		Collection<Route> res;
		
		res = this.routeRepository.findRoutesByEvent(e.getId());
		Assert.notNull(res,"event routes collection found is null");
		
		return res;
	}
	
	public Collection<Route> findAllByAdministrator(Administrator a){
		Assert.notNull(a, "tied to find routes of a null administrator");
		Assert.isTrue(a.getId()!=0, "tried to find routes of and administrator with id zero");
		
		Collection<Route> res;
		
		res = this.routeRepository.findAllByAdmin(a.getId());
		Assert.notNull(res,"admin routes collection found is null");
		
		return res;
	}
}
